package android.pot.com.smartcar.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.entity.ProtocolEntity;
import android.pot.com.smartcar.ui.register.RegisterProtocolActivity;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.TextCheckUtil;
import android.support.v4.app.DialogFragment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaoshilu on 2017/7/24.
 */
@SuppressLint("ValidFragment")
public class XieyiDialogView extends DialogFragment implements View.OnClickListener{

    private Context context;

    public XieyiDialogView(Context context) {
        this.context = context;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View v = inflater.inflate(R.layout.dialog_xieyi, null);
        getDialog().getWindow().getAttributes().windowAnimations = R.style.dialog_up_down;
        getProtocol();
        initBody(v);
        addListener();
        return v;
    }


    @Override
    public void onStart() {
        super.onStart();
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        getDialog().getWindow().setGravity(Gravity.CENTER);
        WindowManager.LayoutParams params = getDialog().getWindow()
                .getAttributes();
        params.width = dm.widthPixels*3/4;
        params.height = params.height;

        getDialog().getWindow().setAttributes(params);
        this.setCancelable(false);
        // 背景透明
        getDialog().getWindow().setBackgroundDrawable(
                new ColorDrawable(Color.TRANSPARENT));
    }

    private void initBody(View v) {
        TextView tv_left = v.findViewById(R.id.tv_cancle);
        TextView tv_right = v.findViewById(R.id.tv_sure);
        TextView tv_tip = v.findViewById(R.id.tv_tip);
        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        SpannableString spannableString = new SpannableString(tv_tip.getText().toString());
        //传入一个MyClickText，并且继承ClickableSpan（必须这样写啊）
        spannableString.setSpan(new MyClickText(1), 48, 54, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new MyClickText(2), 55, 61, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

//        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#8b0000")), 48,53, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#8b0000")), 55,60, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tv_tip.setText(spannableString);
        tv_tip.setMovementMethod(LinkMovementMethod.getInstance());
        tv_tip.setHighlightColor(Color.parseColor("#00000000")); //设置点击后的颜色为透明
    }
    private ProtocolEntity yonghuEntity,yinsiEntity;

    private void getProtocol(){
        Map<String, String> params = new HashMap<String, String>();

        Action.get().protocol_list(context, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message, JSONObject response) {
                try {
                    JSONArray jsonArray  = response.getJSONArray("data");
                    List<ProtocolEntity> list =  GsonUtil.getObjectList(jsonArray.toString(), ProtocolEntity.class);
                    for (ProtocolEntity entity:list){
                        if (entity.getTitle().contains("用户")){
                            yonghuEntity = entity;
                        }
                        if (entity.getTitle().contains("隐私")){
                            yinsiEntity = entity;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }


    private class MyClickText extends ClickableSpan {
        private int  type;
        public MyClickText(int type) {
            this.type = type;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            //设置文本的颜色
            ds.setColor(Color.RED);
            //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            if (type == 1) {
                if (null != yonghuEntity) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", TextCheckUtil.CheckString(yonghuEntity.getUrl()));
                    bundle.putString("title", TextCheckUtil.CheckString(yonghuEntity.getTitle()));
                    Intent intent = new Intent();
                    intent.setClass(context, RegisterProtocolActivity.class);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            }else{
                if (null != yinsiEntity) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", TextCheckUtil.CheckString(yinsiEntity.getUrl()));
                    bundle.putString("title", TextCheckUtil.CheckString(yinsiEntity.getTitle()));
                    Intent intent = new Intent();
                    intent.setClass(context, RegisterProtocolActivity.class);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            }
        }
    }

    private void addListener(){
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_cancle:
                dismiss();
                System.exit(0);
                break;
            case R.id.tv_sure:
                if (listener!=null) {
                    listener.methodClick();
                }
                dismiss();
                break;

        }
    }
    private OnMethodClickListener listener;

    public interface OnMethodClickListener {
        void methodClick();
    }

    public void setMethodClickListener(OnMethodClickListener listener) {
        this.listener = listener;
    }
}

